// DOM元素
const uploadArea = document.getElementById('uploadArea');
const fileInput = document.getElementById('fileInput');
const uploadBtn = document.getElementById('uploadBtn');
const progressBar = document.getElementById('progressBar');
const progressFill = document.getElementById('progressFill');
const resultSection = document.getElementById('resultSection');
const shareUrl = document.getElementById('shareUrl');
const copyBtn = document.getElementById('copyBtn');
const viewBtn = document.getElementById('viewBtn');
const exportHtmlBtn = document.getElementById('exportHtmlBtn');
const notification = document.getElementById('notification');

// 事件监听器
uploadBtn.addEventListener('click', () => fileInput.click());
fileInput.addEventListener('change', handleFileSelect);

// 拖拽上传功能
uploadArea.addEventListener('dragover', handleDragOver);
uploadArea.addEventListener('dragleave', handleDragLeave);
uploadArea.addEventListener('drop', handleDrop);

// 处理文件选择
function handleFileSelect(event) {
    const file = event.target.files[0];
    if (file) {
        validateAndUploadFile(file);
    }
}

// 处理拖拽悬停
function handleDragOver(event) {
    event.preventDefault();
    uploadArea.classList.add('dragover');
}

// 处理拖拽离开
function handleDragLeave(event) {
    event.preventDefault();
    uploadArea.classList.remove('dragover');
}

// 处理文件拖拽放下
function handleDrop(event) {
    event.preventDefault();
    uploadArea.classList.remove('dragover');
    
    const files = event.dataTransfer.files;
    if (files.length > 0) {
        validateAndUploadFile(files[0]);
    }
}

// 验证并上传文件
function validateAndUploadFile(file) {
    // 检查文件类型
    if (!file.name.toLowerCase().endsWith('.md')) {
        showNotification('请选择.md格式的Markdown文件', 'error');
        return;
    }
    
    // 检查文件大小 (5MB)
    if (file.size > 5 * 1024 * 1024) {
        showNotification('文件大小不能超过5MB', 'error');
        return;
    }
    
    uploadFile(file);
}

// 上传文件
function uploadFile(file) {
    const formData = new FormData();
    formData.append('markdown', file);
    
    // 显示进度条
    progressBar.style.display = 'block';
    progressFill.style.width = '0%';
    
    // 禁用上传区域
    uploadArea.style.pointerEvents = 'none';
    uploadArea.style.opacity = '0.7';
    
    // 创建XMLHttpRequest以支持进度监控
    const xhr = new XMLHttpRequest();
    
    // 监听上传进度
    xhr.upload.addEventListener('progress', (event) => {
        if (event.lengthComputable) {
            const percentComplete = (event.loaded / event.total) * 100;
            progressFill.style.width = percentComplete + '%';
        }
    });
    
    // 监听响应
    xhr.addEventListener('load', () => {
        // 恢复上传区域
        uploadArea.style.pointerEvents = 'auto';
        uploadArea.style.opacity = '1';
        progressBar.style.display = 'none';
        
        if (xhr.status === 200) {
            const response = JSON.parse(xhr.responseText);
            handleUploadSuccess(response);
        } else {
            const error = JSON.parse(xhr.responseText);
            showNotification(error.error || '上传失败', 'error');
        }
    });
    
    // 监听错误
    xhr.addEventListener('error', () => {
        uploadArea.style.pointerEvents = 'auto';
        uploadArea.style.opacity = '1';
        progressBar.style.display = 'none';
        showNotification('网络错误，请重试', 'error');
    });
    
    // 发送请求
    xhr.open('POST', '/api/upload');
    xhr.send(formData);
}

// 处理上传成功
function handleUploadSuccess(response) {
    showNotification('文件上传成功！', 'success');
    
    // 显示结果区域
    resultSection.style.display = 'block';
    
    // 设置分享链接
    shareUrl.value = response.shareUrl;
    
    // 设置按钮链接
    viewBtn.href = response.shareUrl;
    exportHtmlBtn.href = `/api/export/html/${response.shareId}`;
    
    // 滚动到结果区域
    resultSection.scrollIntoView({ behavior: 'smooth' });
    
    // 重置文件输入
    fileInput.value = '';
    
    // 刷新最近文档列表
    setTimeout(() => {
        loadRecentDocuments();
    }, 1000);
}

// 复制分享链接
function copyShareUrl() {
    shareUrl.select();
    shareUrl.setSelectionRange(0, 99999); // 移动端兼容
    
    try {
        document.execCommand('copy');
        showNotification('链接已复制到剪贴板', 'success');
        
        // 临时改变按钮文本
        const originalText = copyBtn.textContent;
        copyBtn.textContent = '已复制！';
        setTimeout(() => {
            copyBtn.textContent = originalText;
        }, 2000);
    } catch (err) {
        // 如果复制失败，尝试使用现代API
        if (navigator.clipboard) {
            navigator.clipboard.writeText(shareUrl.value).then(() => {
                showNotification('链接已复制到剪贴板', 'success');
            }).catch(() => {
                showNotification('复制失败，请手动复制', 'error');
            });
        } else {
            showNotification('复制失败，请手动复制', 'error');
        }
    }
}

// 显示通知
function showNotification(message, type = 'info') {
    notification.textContent = message;
    notification.className = `notification ${type}`;
    notification.classList.add('show');
    
    // 3秒后自动隐藏
    setTimeout(() => {
        notification.classList.remove('show');
    }, 3000);
}

// 页面加载完成后的初始化
document.addEventListener('DOMContentLoaded', () => {
    // 检查是否支持拖拽上传
    if (!('FileReader' in window) || !('FormData' in window)) {
        showNotification('您的浏览器不支持文件上传功能，请升级浏览器', 'error');
    }
    
    // 添加复制按钮点击事件
    copyBtn.addEventListener('click', copyShareUrl);
    
    // 防止页面默认的拖拽行为
    document.addEventListener('dragover', (e) => e.preventDefault());
    document.addEventListener('drop', (e) => e.preventDefault());
    
    // 加载最近文档
    loadRecentDocuments();
});

// 加载最近文档
async function loadRecentDocuments() {
    const recentDocumentsGrid = document.getElementById('recentDocumentsGrid');
    const documentsLoading = document.getElementById('documentsLoading');
    
    try {
        const response = await fetch('/api/recent-documents');
        
        if (!response.ok) {
            throw new Error('获取文档列表失败');
        }
        
        const documents = await response.json();
        
        // 隐藏加载状态
        documentsLoading.style.display = 'none';
        
        if (documents.length === 0) {
            // 显示空状态
            recentDocumentsGrid.innerHTML = `
                <div class="empty-state">
                    <div class="empty-state-icon">📄</div>
                    <p>暂无文档，快来上传第一个吧！</p>
                </div>
            `;
            return;
        }
        
        // 渲染文档列表
        recentDocumentsGrid.innerHTML = documents.map(doc => {
            const uploadTime = new Date(doc.uploadTime).toLocaleString('zh-CN', {
                year: 'numeric',
                month: 'short',
                day: 'numeric',
                hour: '2-digit',
                minute: '2-digit'
            });
            
            return `
                <div class="document-card" onclick="window.open('${doc.shareUrl}', '_blank')">
                    <div class="document-title">${escapeHtml(doc.title)}</div>
                    <div class="document-meta">
                        <div class="document-time">
                            <span>🕒</span>
                            <span>${uploadTime}</span>
                        </div>
                        <div class="document-views">
                            <span>👁️</span>
                            <span>${doc.views}</span>
                        </div>
                    </div>
                    <div class="document-actions">
                        <a href="${doc.shareUrl}" class="preview-btn" target="_blank" onclick="event.stopPropagation()">📖 在线预览</a>
                    </div>
                </div>
            `;
        }).join('');
        
    } catch (error) {
        console.error('加载最近文档失败:', error);
        documentsLoading.innerHTML = `
            <div class="empty-state">
                <div class="empty-state-icon">❌</div>
                <p>加载失败，请刷新页面重试</p>
            </div>
        `;
    }
}

// HTML转义函数
function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// 工具函数：格式化文件大小
function formatFileSize(bytes) {
    if (bytes === 0) return '0 Bytes';
    
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// 工具函数：检查网络连接
function checkNetworkConnection() {
    return navigator.onLine;
}

// 监听网络状态变化
window.addEventListener('online', () => {
    showNotification('网络连接已恢复', 'success');
});

window.addEventListener('offline', () => {
    showNotification('网络连接已断开', 'error');
});

// 错误处理
window.addEventListener('error', (event) => {
    console.error('页面错误:', event.error);
});

// 未处理的Promise拒绝
window.addEventListener('unhandledrejection', (event) => {
    console.error('未处理的Promise拒绝:', event.reason);
    event.preventDefault();
});